import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import java.io.File;
import java.io.IOException;

/**
 * AppInstaller.java
 *
 * Copyright (C) 2013 Timo Tegtmeier.
 * All rights reserved.
 */

public class AppInstaller {

    private static int APP_STATUS_INSTALLED = 1;
    private static int APP_STATUS_PRIVILEGED = 2;
    private static int APP_STATUS_CERTIFIED = 3;

    private DebuggerTransport transport;

    public AppInstaller(DebuggerTransport transport) {
        this.transport = transport;
    }

    public void installApp(String path) throws IOException {
        File appPackage = new File(path);
        if(!appPackage.exists()) {
            System.out.println("Package does not exist!");
            return;
        }

        String inputPath = appPackage.getAbsolutePath();
        String appId = appPackage.getParentFile().getName();
        String devicePath = "/data/local/tmp/b2g/" + appId + "/application.zip";

        if(!AdbWrapper.pushFile(inputPath, devicePath)) {
            System.out.println("Unable to push app package to device!");
            return;
        }

        String webAppActor = getWebAppsActor();
        doInstallApp(webAppActor, appId);
    }

    private String getWebAppsActor() throws IOException {
        JSONObject cmd = new JSONObject();
        cmd.put("to", "root");
        cmd.put("type", "listTabs");
        transport.sendMessage(cmd);

        JSONObject result = (JSONObject)JSONValue.parse(transport.receiveAnswer());
        return (String)result.get("webappsActor");
    }

    private void doInstallApp(String actor, String appId) throws IOException {
        JSONObject cmd = new JSONObject();
        cmd.put("to", actor);
        cmd.put("type", "install");
        cmd.put("appId", appId);
        cmd.put("appType", APP_STATUS_INSTALLED);
        transport.sendMessage(cmd.toJSONString());

        JSONObject result = (JSONObject)JSONValue.parse(transport.receiveAnswer());
        if(result.containsKey("error"))
            System.out.println(String.format("Failed to install app: ", result.get("error")));
    }
}
